package com.labofjet.system.util;

import com.labofjet.common.dto.ContextDto;
import com.labofjet.common.util.StringHelper;
import org.apache.commons.collections.MapUtils;

import java.util.Map;
import java.util.TreeMap;

public class RedisCacheUtils {

	public static final String SPERATOR = "|";

	/**
	 * 计算page缓存的key
	 *
	 * @param contextDto
	 * @return
	 */
	public static String calcKey(ContextDto contextDto) {
		Map<String, Object> requestParams = new TreeMap<>(contextDto.getRequestParams());
		if (MapUtils.isEmpty(requestParams)) {
			return "";
		}
		StringBuilder b = new StringBuilder();
		for (Map.Entry<String, Object> entry : requestParams.entrySet()) {
			Object v = entry.getValue();
			if (v != null) {
				b.append(StringHelper.defaultIfEmpty(v, null)).append("|");
			}
		}
		return b.toString();
	}

	/**
	 * 计算page缓存的key,可以指定参数名
	 * @param contextDto
	 * @param kName
	 * @return
	 */
	public static String calcKey(ContextDto contextDto, String... kName) {
		Map<String, Object> requestParams = new TreeMap<>(contextDto.getRequestParams());
		if (MapUtils.isEmpty(requestParams)) {
			return "";
		}
		StringBuilder b = new StringBuilder();
		for (String s : kName) {
			b.append(StringHelper.defaultIfEmpty(requestParams.get(s), null)).append("|");
		}
		return b.toString();
	}

	/**
	 * 计算id缓存的key
	 * @param contextDto
	 * @return
	 */
	public static String calcIdKey(ContextDto contextDto) {
		Map<String, Object> requestParams = contextDto.getRequestParams();
		return StringHelper.defaultIfEmpty(requestParams.get("id"), null);
	}

	/**
	 * 计算多个id缓存的key
	 *
	 * @param contextDto
	 * @return
	 */
	public static String calcIdsKey(ContextDto contextDto) {
		Map<String, Object> requestParams = contextDto.getRequestParams();
		return StringHelper.defaultIfEmpty(requestParams.get("id"), null);
	}

	public static String evictIdKey(Integer id) {
		return StringHelper.toString(id);
	}
}

